import { useState, createRef } from "react";

import { Navigate } from "react-router-dom";

function UserLogin(){

  // 声明一个叫 `user` 的 state 变量
  const [user, setUser] = useState( null );
  // 声明一个叫 `reason` 的 state 变量
  const [reason,setReason] = useState( '' );

  const accountRef = createRef();
  const passwordRef = createRef();

  const handleSubmit = evt => {
    evt.preventDefault();
    
    // const form = evt.target ;
    // console.log( form.account.value );
    // console.log( form.password.value );

    let account = accountRef.current.value;
    let password = passwordRef.current.value;
    console.log( account , password );

    if( 'sanfeng' === account && 'hello' === password ) {
        // 修改 state 中的 user 变量
        setUser( { account, password } );
        return;
    }
    
    setReason('账号或密码错误');
  }

  return (
    <div className="login-form">
      <div>{ reason && <p>{reason}</p> }</div>
      { user && <Navigate to="/user/main" replace={true} /> }
      <form onSubmit={ handleSubmit }>
        <input type="text" name="account" placeholder="登录账号" ref={ accountRef }/>
        <input type="password" name="password" placeholder="登录密码" ref={ passwordRef } />
        <button>登录</button>
      </form>
    </div>
  )
}

export default UserLogin;